先走一遍linked-list把要反轉的推進stack,再重走一遍把數值改掉(btw順便複習可愛的林可得利私><)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
stack<int> st;
ListNode *curr = head;
int count = 1;
while(curr){
if(count >= left && count <= right){
st.push(curr->val);
}
curr = curr->next;
count++;
}
curr = head;
count = 1;
while(curr){
if(count >= left && count <= right){
curr->val = st.top();
st.pop();
}
curr = curr->next;
count++;
}
return head;
}
};